package com.example.fido2013;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapScreen extends Activity {

	static final LatLng GTTSRB = new LatLng(33.77712, -84.39010);
	private static GoogleMap map;
	ArrayList<JSONObject> incidentList;
	ArrayList<JSONObject> broadcastList;
	String sessionName;
	String sessionId;
	
	ArrayList<JSONObject> allDogDetails;
	ArrayList<Marker> markerArrayList;
	
	private static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
	
	HashMap<String, JSONObject> incidentHashMap = new HashMap<String, JSONObject>();

	final Context context = this;
	
	Timer timer;
	String updateInterval;
	
	CheckBox realTimeTrackingCheckbox;
	CheckBox realTimeTrackingCheckboxAll;
	
	double thisLatitude = 33.234;
	double thisLongitude = -84.345;
	LatLng thisLatLng = new LatLng(thisLatitude, thisLongitude);
	Marker myMarker; 
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_screen);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MapScreen.this);
		SharedPreferences.Editor editor = prefs.edit();
		sessionName = prefs.getString("sessionName", "null");
		sessionId = prefs.getString("sessionId", "null");
		
		markerArrayList = new ArrayList<Marker>();

		APICallAsync apiCall = new APICallAsync("http://dev.m.gatech.edu/d/sraghu3/w/fidocpy/c/api/incident", sessionName, sessionId, MapScreen.this);
		try {
			incidentList = apiCall.execute().get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		
		myMarker = map.addMarker(new MarkerOptions().position(thisLatLng).title("initial marker")
				.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
		myMarker.setVisible(false);

		Intent intent = getIntent();
		if (intent.getExtras() == null) {
			map.setMyLocationEnabled(true);

			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			Criteria criteria = new Criteria();
			String provider = locationManager.getBestProvider(criteria, true);
			Location myLocation = locationManager.getLastKnownLocation(provider);

			double latitude = myLocation.getLatitude();
			double longitude = myLocation.getLongitude();
			LatLng myLatLng = new LatLng(latitude, longitude);

			markLocation(myLatLng, false, null);
			CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(myLatLng, 18);
			map.animateCamera(cameraUpdate);
		} else {
			map.setMyLocationEnabled(true);

			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			Criteria criteria = new Criteria();
			String provider = locationManager.getBestProvider(criteria, true);
			Location myLocation = locationManager.getLastKnownLocation(provider);

			double latitude = myLocation.getLatitude();
			double longitude = myLocation.getLongitude();
			LatLng myLatLng = new LatLng(latitude, longitude);

			markLocation(myLatLng, false, null);

			Double lat = intent.getDoubleExtra("latitude", 0);
			Double lon = intent.getDoubleExtra("longitude", 0);
			LatLng latLng = new LatLng(lat, lon);
			CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
			map.animateCamera(cameraUpdate);
		}
		
		APICallAsync dogVestApiCall = new APICallAsync("http://dev.m.gatech.edu/d/vkrishnan35/w/fidocpy/c/api/vests/", sessionName, sessionId, MapScreen.this);
		ArrayList<JSONObject> dogVestList = null;
		try {
			dogVestList = dogVestApiCall.execute().get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		String dogVestNames = "";
		for (int i = 0; i < dogVestList.size(); i++) {
			try {
				dogVestNames = dogVestNames + dogVestList.get(i).get("dogName").toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} 
		
		final String finalDogVestNames = dogVestNames;

		map.setOnMarkerClickListener(new OnMarkerClickListener() {
			public boolean onMarkerClick(Marker marker) {
				
				boolean isValidTitle = finalDogVestNames.contains(marker.getTitle());
				
				if (marker.getTitle().equals("Your Location") || isValidTitle) {
					marker.showInfoWindow();
				} 
				else {
					JSONObject incident = incidentHashMap.get(marker.getId());
					try {
						showIncidentDialog(false, Integer.parseInt(incident.get("id").toString()), incident.get("latitude").toString(), incident.get("longitude").toString(), incident.get("bombType").toString(), incident.get("bombIsActive").toString(), true, incident.get("dogID").toString(), incident.get("dogvest").toString(), incident.get("timeFound").toString());
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				return true;
			}
		});
		
		checkForNewIncidents();
		checkForNewBroadcasts();

		int numIncidents = incidentList.size();
		int numBroadcasts = broadcastList.size();
		try {
			String oldLastIncident = incidentList.get(numIncidents - 1).get("timeFound").toString();
			String currentLastIncident = oldLastIncident;
			editor.putString("oldLastIncident", oldLastIncident);
			editor.putString("currentLastIncident", currentLastIncident);
			
			String oldLastBroadcast = broadcastList.get(numBroadcasts - 1).get("timeFound").toString();
			String currentLastBroadcast = oldLastBroadcast;
			editor.putString("oldLastBroadcast", oldLastBroadcast);
			editor.putString("currentLastBroadcast", currentLastBroadcast);
			
			editor.commit();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean AreWeOnline(Context context) {
	      ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
	       
	      NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
	      return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
	}

	public void markLocation(LatLng latLng, Boolean incidentMarker, JSONObject incident) {

		if (incidentMarker) {
			Marker myMarker = map.addMarker(new MarkerOptions().position(latLng).title("Incident")
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

			incidentHashMap.put(myMarker.getId(), incident);
		} else if (!incidentMarker) {
			Marker myMarker = map.addMarker(new MarkerOptions().position(latLng).title("Your Location")
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
		}
	}

	public void showIncidentDialog(boolean isBroadcast, final int ID, final String lat, final String lon, final String bombType, final String isActive, boolean mapIncident, final String dogID, final String dogvest, final String timeFound) {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.custom_dialog_box);
		LayoutInflater inflater = MapScreen.this.getLayoutInflater();
		
		if (!mapIncident) {
			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			v.vibrate(500);
		}

		View dialogView = inflater.inflate(R.layout.custom_dialog_box, null);
		dialog.setContentView(dialogView);

		if (mapIncident) {
			dialog.setTitle("Threat detected by " + dogvest + ".");
		}
		if (isBroadcast) {
			dialog.setTitle("New Broadcast.");
		}	
		else {
			dialog.setTitle("New Threat Detected.");
		}
		TextView bombTypeTextView = (TextView) dialogView.findViewById(R.id.bombTypeTextView);
		TextView activeOrNotTextView = (TextView) dialogView.findViewById(R.id.bombStatusTextView);
		TextView addressLine1TextView = (TextView) dialogView.findViewById(R.id.bombAddressTextViewLine1);

		bombTypeTextView.setText(bombType);

		if (isActive.equals("Y")) {
			activeOrNotTextView.setText("Active");
		} else {
			activeOrNotTextView.setText("Innactive");
		}

		String address = getAddress(Float.parseFloat(lat), Float.parseFloat(lon));
		int breakIndex = address.indexOf("\n");
		addressLine1TextView.setText(address);
		
		if (!mapIncident) {
			
			Notification n  = new Notification.Builder(this)
	        .setContentTitle("New " + bombType + " bomb found at " + address)
	        .setSmallIcon(R.drawable.dog)
	        .setAutoCancel(true)
	        .build();    
					
			NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			notificationManager.notify(0, n);
			
		}
		
		if (mapIncident) {
			Button navigateButton = (Button) dialog.findViewById(R.id.navigateButton);
			navigateButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					map.setMyLocationEnabled(true);
	
					LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
					Criteria criteria = new Criteria();
					String provider = locationManager.getBestProvider(criteria, true);
					Location myLocation = locationManager.getLastKnownLocation(provider);
	
					double myLat = myLocation.getLatitude();
					double myLon = myLocation.getLongitude();
	
					Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + myLat + "," + myLon
							+ "&daddr=" + lat + "," + lon));
					startActivity(intent);
	
					dialog.dismiss();
				}
			});
		}
		else {
			Button navigateButton = (Button) dialog.findViewById(R.id.navigateButton);
			navigateButton.setText("Map");
			navigateButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					
					Intent i = new Intent(MapScreen.this, MapScreen.class);
					i.putExtra("latitude", Double.parseDouble(lat));
					i.putExtra("longitude", Double.parseDouble(lon));
					startActivity(i);					
					dialog.dismiss();
					finish();
				}
			});
		}

		Button broadcastAlertButton = (Button) dialog.findViewById(R.id.broadcastAlertButton);
		broadcastAlertButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent broadcastIntent = new Intent(MapScreen.this, BroadcastChoiceScreen.class);
				broadcastIntent.putExtra("lat", lat);
				broadcastIntent.putExtra("lon", lon);
				broadcastIntent.putExtra("bombType", bombType);
				broadcastIntent.putExtra("isActive", isActive);
				broadcastIntent.putExtra("dogID", dogID);
				broadcastIntent.putExtra("dogvest", dogvest);
				broadcastIntent.putExtra("alerting activity", "MainMenu");
				
				dialog.dismiss();
				
				startActivity(broadcastIntent);	
			}
		});

		Button dismissButton = (Button) dialog.findViewById(R.id.dismissButton);
		if (!mapIncident) {
			dismissButton.setText("  Dismiss Alert ");
		}
		dismissButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new UpdateIncidentTask(ID).execute();
				Intent i = new Intent(MapScreen.this, MapScreen.class);
				startActivity(i);
				dialog.dismiss();
				finish();
			}
		});

		dialog.show();
		
		if (isBroadcast) {
			broadcastAlertButton.setEnabled(false);
		}
		else {
			broadcastAlertButton.setEnabled(true);
		}
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MapScreen.this);
		String displayTimeMinutes = prefs.getString("display time minutes", "null");
		String displayTimeSeconds = prefs.getString("display time seconds", "null");
		
		int displayTimeMinutesInt;
		int displayTimeSecondsInt;
		
		if (displayTimeMinutes.equals("null") || displayTimeMinutes.equals("")) {
			displayTimeMinutesInt = 0;
		}
		else {
			displayTimeMinutesInt = Integer.parseInt(displayTimeMinutes);
		}
		
		if (displayTimeSeconds.equals("null") || displayTimeSeconds.equals("")) {
			displayTimeSecondsInt = 0;
		}
		else {
			displayTimeSecondsInt = Integer.parseInt(displayTimeSeconds);
		}		
		
		int totalTimeToDisplay = (((displayTimeMinutesInt * 60) + displayTimeSecondsInt)) * 1000;
		
		if (displayTimeMinutesInt != 0 || displayTimeSecondsInt != 0) {
			Timer dialogTimer = new Timer();
			dialogTimer.schedule(new TimerTask() {
				
				public void run() {
					dialog.dismiss();
				}
				
			}, totalTimeToDisplay);
		}
	}
	
	public void onPause() {
		super.onPause();
		timer.cancel();
	}

	private String getAddress(double latitude, double longitude) {
		StringBuilder result = new StringBuilder();
		try {
			Geocoder geocoder = new Geocoder(this, Locale.getDefault());
			List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
			if (addresses.size() > 0) {
				Address address = addresses.get(0);
				result.append(address.getAddressLine(0)).append("\n");
				result.append(address.getLocality()).append(", " + address.getAdminArea()).append("\n");
			}
		} catch (IOException e) {
			Log.e("tag", e.getMessage());
		}

		return result.toString();
	}

	public void onResume() {
		super.onResume();

		HashMap<String, JSONObject> incidentHashMap = new HashMap<String, JSONObject>();

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MapScreen.this);
		String numIncidentsToShow = prefs.getString("number of incidents to show", "null");
		
		int incidentsToShow = 0;
		if (numIncidentsToShow.equals("null") || numIncidentsToShow.equals("")) {
			incidentsToShow = 10;
		}
		else {
			incidentsToShow = Integer.parseInt(numIncidentsToShow);
		}
		
		System.out.println(incidentList.size() - incidentList.size() + incidentsToShow);
		
		for (int i = incidentList.size() - incidentsToShow; i < incidentList.size(); i++) {
			double latitude = 0;
			double longitude = 0;
			String bombIsActive = "";
			String bombType = "";
			try {
				latitude = Double.parseDouble(incidentList.get(i).get("latitude").toString());
				longitude = Double.parseDouble(incidentList.get(i).get("longitude").toString());
				bombIsActive = incidentList.get(i).get("bombIsActive").toString();
				bombType = incidentList.get(i).get("bombType").toString();

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			LatLng latLng = new LatLng(latitude, longitude);
			
			if (bombIsActive.equals("Y") && !bombType.equals("test")) {
				markLocation(latLng, true, incidentList.get(i));
			}
		}		
				
		updateInterval = prefs.getString("update interval", "null");
		if (updateInterval.equals("null")) {
			updateInterval = "10000";
		} else if (updateInterval.substring(3).equals("min")) {
			int tempInt = Integer.parseInt(updateInterval.substring(0, 2));
			tempInt = tempInt * 60 * 1000;
			updateInterval = Integer.toString(tempInt);
			System.out.println(updateInterval);
		} else {
			updateInterval = updateInterval.substring(0, 2) + "000";
			System.out.println(updateInterval);
		}

		startCheckingIncidents();
		
		realTimeTrackingCheckbox = (CheckBox) findViewById(R.id.justMyDogCheckbox);
		realTimeTrackingCheckboxAll = (CheckBox) findViewById(R.id.allDogsCheckBox);
		if (!prefs.getString("subscribed dog vest", "null").equals("null")) {
			realTimeTrackingCheckbox.setText("Just " + prefs.getString("subscribed dog vest", "null"));
		}
		else if (prefs.getString("subscribed dog vest", "null").equals("null")) {
			realTimeTrackingCheckbox.setText("Just " + "nothing");
		}
		
		realTimeTrackingCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked == true) {
					realTimeTrackingCheckboxAll.setChecked(false);
					
					if (markerArrayList != null) {
						runOnUiThread(new Runnable() {
							public void run() {								
								for (int y = 0; y < markerArrayList.size(); y++) {
									Marker thisMarker = markerArrayList.get(y);
									thisMarker.remove();
								}
								markerArrayList.clear();
							}						    
						});
					}
				}
				if (isChecked == false) {
					realTimeTrackingCheckbox.setChecked(false);
					
					if (myMarker != null) {
						myMarker.remove();
					}
				}
			}
			
		});
		
		realTimeTrackingCheckboxAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked == true) {
					realTimeTrackingCheckbox.setChecked(false);
					
					if (myMarker != null) {
						myMarker.remove();
					}
				}
				if (isChecked == false) {
					realTimeTrackingCheckboxAll.setChecked(false);
					
					if (markerArrayList != null) {
						runOnUiThread(new Runnable() {
							public void run() {								
								for (int y = 0; y < markerArrayList.size(); y++) {
									Marker thisMarker = markerArrayList.get(y);
									thisMarker.remove();
								}
								markerArrayList.clear();
							}						    
						});
					}
				}
			}
			
		});
		
		// TODO figure out how to add a new marker as soon as this is checked yes and remove it as soon as it is checked back to no
	}
	
	public void checkForNewIncidents() {
		APICallAsync apiCall = new APICallAsync("http://dev.m.gatech.edu/d/sraghu3/w/fidocpy/c/api/incident", sessionName, sessionId, MapScreen.this);
		try {
			incidentList = apiCall.execute().get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	public void checkForNewBroadcasts() {
		APICallAsync apiCall = new APICallAsync("http://dev.m.gatech.edu/d/amartin37/w/fidocpy/c/api/broadcast", sessionName, sessionId, MapScreen.this);
		try {
			broadcastList = apiCall.execute().get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	public void startCheckingIncidents() { 
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {

			public void run() {
				if (AreWeOnline(MapScreen.this)) {
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MapScreen.this);
					SharedPreferences.Editor editor = prefs.edit();
					String oldLastIncident = prefs.getString("oldLastIncident", "null");
					String currentLastIncident = prefs.getString("currentLastIncident", "null");
	
					String incidentDog = "";
					final String currentlySelectedVest = prefs.getString("subscribed dog vest", "null");
					int currentlySelectedVestID = prefs.getInt("subscribed dog vest ID", 1000);
	
					final ArrayList<JSONObject> thisIncidentList = new APICallIncidentsNoAsync(sessionName, sessionId).checkForNewIncidentsNoAsync();
					final int numIncidents = thisIncidentList.size();
					try {
						currentLastIncident = thisIncidentList.get(numIncidents - 1).get("timeFound").toString(); 
						incidentDog = thisIncidentList.get(numIncidents - 1).get("dogvest").toString();
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (currentLastIncident.equals(oldLastIncident)) {
						System.out.println("no new incident found");
					} else if (!currentLastIncident.equals(oldLastIncident) && (!incidentDog.equals(currentlySelectedVest))) {
						oldLastIncident = currentLastIncident;
						editor.putString("oldLastIncident", oldLastIncident);
						editor.putString("currentLastIncident", currentLastIncident);
						editor.commit();
						System.out.println("new incident found, but not the right vest");
					} else if (!currentLastIncident.equals(oldLastIncident) && (incidentDog.equals(currentlySelectedVest))) {
						oldLastIncident = currentLastIncident;
						editor.putString("oldLastIncident", oldLastIncident);
						editor.putString("currentLastIncident", currentLastIncident);
						editor.commit();
						System.out.println("new incident found and is the right vest");
						try {
							final int id = Integer.parseInt(thisIncidentList.get(numIncidents - 1).get("id").toString());
							final String latitude = thisIncidentList.get(numIncidents - 1).get("latitude").toString();
							final String longitude = thisIncidentList.get(numIncidents - 1).get("longitude").toString();
							final String bombType = thisIncidentList.get(numIncidents - 1).get("bombType").toString();
							final String bombIsActive = thisIncidentList.get(numIncidents - 1).get("bombIsActive").toString();
							
							final String dogID = thisIncidentList.get(numIncidents - 1).get("dogID").toString();
							final String dogvest = thisIncidentList.get(numIncidents - 1).get("dogvest").toString();
							final String timeFound = thisIncidentList.get(numIncidents - 1).get("timeFound").toString();
	
							MapScreen.this.runOnUiThread(new Runnable() {
								public void run() {
									showIncidentDialog(false, id, latitude, longitude, bombType, bombIsActive, false, dogID, dogvest, timeFound);
								}
							});
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}					
										
					String oldLastBroadcast = prefs.getString("oldLastBroadcast", "null");
					String currentLastBroadcast = prefs.getString("currentLastBroadcast", "null");
					String myUserType = prefs.getString("user type", "P");
					String broadcastDog = "";
					
					String userType = null;
					
					final ArrayList<JSONObject> thisBroadcastList = new APICallBroadcastsNoAsync(sessionName, sessionId).checkForNewBroadcastsNoAsync();
					final int numBroadcasts = thisBroadcastList.size();
					try {
						currentLastBroadcast = thisBroadcastList.get(numBroadcasts - 1).get("timeFound").toString(); 
						broadcastDog = thisBroadcastList.get(numBroadcasts - 1).get("dogvest").toString();
						userType = thisBroadcastList.get(numBroadcasts - 1).get("userType").toString();
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
					boolean myUserTypePresent = userType.contains(myUserType);
					
					if (currentLastBroadcast.equals(oldLastBroadcast)) {
						System.out.println("no new broadcast found");
					} else if (!currentLastBroadcast.equals(oldLastBroadcast) && (broadcastDog.equals(currentlySelectedVest))) {
						oldLastBroadcast = currentLastBroadcast;
						editor.putString("oldLastBroadcast", oldLastBroadcast);
						editor.putString("currentLastBroadcast", currentLastBroadcast);
						editor.commit();
						System.out.println("new broadcast found, but it was from this vest");
					} else if (!currentLastBroadcast.equals(oldLastBroadcast) && !myUserTypePresent) {
							oldLastBroadcast = currentLastBroadcast;
							editor.putString("oldLastBroadcast", oldLastBroadcast);
							editor.putString("currentLastBroadcast", currentLastBroadcast);
							editor.commit();
							System.out.println("new broadcast found, but it was not the right user type");
					} else if (!currentLastBroadcast.equals(oldLastBroadcast) && (!broadcastDog.equals(currentlySelectedVest)) && myUserTypePresent) {
						oldLastBroadcast = currentLastBroadcast;
						editor.putString("oldLastBroadcast", oldLastBroadcast);
						editor.putString("currentLastBroadcast", currentLastBroadcast);
						editor.commit();
						System.out.println("new broadcast found and is not from this vest");
						String showBroadcasts = prefs.getString("show broadcasts", "true");
						if (showBroadcasts.equals("true")) {
							try {
								final int id = Integer.parseInt(thisBroadcastList.get(numBroadcasts - 1).get("id").toString());
								final String latitude = thisBroadcastList.get(numBroadcasts - 1).get("latitude").toString();
								final String longitude = thisBroadcastList.get(numBroadcasts - 1).get("longitude").toString();
								final String bombType = thisBroadcastList.get(numBroadcasts - 1).get("bombType").toString();
								final String bombIsActive = thisBroadcastList.get(numBroadcasts - 1).get("bombIsActive").toString();
								
								final String dogID = thisBroadcastList.get(numBroadcasts - 1).get("dogID").toString();
								final String dogvest = thisBroadcastList.get(numBroadcasts - 1).get("dogvest").toString();
								final String timeFound = thisBroadcastList.get(numBroadcasts - 1).get("timeFound").toString();
		
								MapScreen.this.runOnUiThread(new Runnable() {
									public void run() {
										showIncidentDialog(true, id, latitude, longitude, bombType, bombIsActive, false, dogID, dogvest, timeFound);
									}
								});
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						else if (showBroadcasts.equals("false")) {
							System.out.println("found a broadcast, but I'm not supposed to show it");
						}
					}
					
					boolean realTimeTrack = realTimeTrackingCheckbox.isChecked();
					if (realTimeTrack && currentlySelectedVestID != 1000) {						
						final JSONObject dogDetails = new APICallDogVestsNoAsync(sessionName, sessionId, currentlySelectedVestID).getDogVestDetailsNoAsync();
						runOnUiThread(new Runnable() {
						    public void run() {
						    	
						    	double latitude = 0;
						    	double longitude = 0;
								try {
									latitude = Double.parseDouble(dogDetails.get("latitude").toString());
									longitude = Double.parseDouble(dogDetails.get("longitude").toString());
								} catch (NumberFormatException e) {
									e.printStackTrace();
								} catch (JSONException e) {
									e.printStackTrace();
								}
								
								LatLng latlng = new LatLng(latitude, longitude);
								
								myMarker.remove();
								
						    	myMarker = map.addMarker(new MarkerOptions().position(latlng).title(currentlySelectedVest)
										.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
						    }
						});
					}
					else if (realTimeTrack && currentlySelectedVestID == 1000) {
						runOnUiThread(new Runnable() {
						    public void run() {
						    	Toast.makeText(getBaseContext(), "No dog subscription detected. Please subscribe to a dog to enable tracking.", Toast.LENGTH_LONG).show();
						    }
						});	
					}
					else if (!realTimeTrack) {
						runOnUiThread(new Runnable() {
						    public void run() {
						    	if (myMarker != null) {
									myMarker.remove();
								}
						    }
						});
					}
					
					boolean realTimeTrackAll = realTimeTrackingCheckboxAll.isChecked();
					if (realTimeTrackAll) {		
						
						if (markerArrayList != null) {
							runOnUiThread(new Runnable() {
								public void run() {								
									for (int y = 0; y < markerArrayList.size(); y++) {
										Marker thisMarker = markerArrayList.get(y);
										thisMarker.remove();
									}
									markerArrayList.clear();
								}						    
							});
						}
						
						allDogDetails = new APICallDogvestsArrayNoAsync(sessionName, sessionId).getDogvestsArrayNoAsync();
						// TODO maybe put a .clear() call here to clear the array of all markers after each cycle
						runOnUiThread(new Runnable() {
						    public void run() {
						    	
						    	for (int i = 0; i < allDogDetails.size(); i++) {
						    		double latitude = 0;
							    	double longitude = 0;
							    	String dogName = "";
									try {
										latitude = Double.parseDouble(allDogDetails.get(i).get("latitude").toString());
										longitude = Double.parseDouble(allDogDetails.get(i).get("longitude").toString());
										dogName = allDogDetails.get(i).get("dogName").toString();
									} catch (NumberFormatException e) {
										e.printStackTrace();
									} catch (JSONException e) {
										e.printStackTrace();
									}
									
									LatLng latlng = new LatLng(latitude, longitude);									
									
							    	Marker marker = map.addMarker(new MarkerOptions().position(latlng).title(dogName)
											.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
							    	
							    	markerArrayList.add(marker);							    	
						    	}				
						    }
						});
					}
					else if (!realTimeTrackAll) {
						if (markerArrayList != null) {
							runOnUiThread(new Runnable() {
								public void run() {								
									for (int y = 0; y < markerArrayList.size(); y++) {
										Marker thisMarker = markerArrayList.get(y);
										thisMarker.remove();
									}
									markerArrayList.clear();
								}						    
							});
						}					
					}					
				}
				
				if (!AreWeOnline(MapScreen.this)) {
					runOnUiThread(new Runnable() {
					    public void run() {
					    	Toast.makeText(getBaseContext(), "No network connectivity detected. Please make sure WiFi or 3G/4G data network is available.", Toast.LENGTH_LONG).show();
					    }
					});		        	
		        }
			}
		}, 0, Integer.parseInt(updateInterval));
	}
	
	public class UpdateIncidentTask extends AsyncTask<String, Integer, Void> {

		ProgressDialog progressDialog;
		int incidentID;
		
		public UpdateIncidentTask(int ID) {
			incidentID = ID;
		}

		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(MapScreen.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Marking resolved...");
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		protected Void doInBackground(String... params) {
			
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://dev.m.gatech.edu/d/amartin37/w/fidocpy/c/api/updateincident");
			post.setHeader("Cookie", sessionName + "=" + sessionId);
			
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("id", Integer.toString(incidentID)));
			pairs.add(new BasicNameValuePair("bombIsActive", "N"));
			
			try {
				post.setEntity(new UrlEncodedFormEntity(pairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			try {
				HttpResponse response = client.execute(post);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			Message message = new Message();
			handler.sendMessage(message);
			progressDialog.dismiss();
		}

		private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
//				progressDialog.dismiss();
			}
		};

		protected void onCancelled() {
			super.onCancelled();
		}
	}
}
